import React, {useState, useEffect} from 'react'
import { Form, Input, message } from 'antd'
import { RmbIcon, PercentIcon, DateIcon } from '@components/icon/system'
import classnames from 'classnames'

const rules = {
  amount: [
    {
      required: true,
      message: '请输入已用额度'
    },
    {
      validator: (_, value) => {
        if (value === 0 || value === '0') {
          return Promise.reject(new Error('输入额度必须大于0'));
        }
        return Promise.resolve();
      },
    }
  ],
  interest: [
    {
      required: true,
      message: '请输入年利率'
    },
    {
      validator: (_, value) => {
        if (value === 0 || value === '0') {
          return Promise.reject(new Error('输入年利率必须大于0'));
        }
        return Promise.resolve();
      },
    }
  ],
  minRatio: [
    {
      required: true,
      message: '请输入最低还款比例'
    },
    {
      validator: (_, value) => {
        if (value === 0 || value === '0') {
          return Promise.reject(new Error('输入最低还款比例必须大于0'));
        }
        return Promise.resolve();
      },
    }
  ],
  payment: [
    {
      required: true,
      message: '请输入每月还款金额'
    },
    {
      validator: (_, value) => {
        if (value === 0 || value === '0') {
          return Promise.reject(new Error('输入每月还款金额必须大于0'));
        }
        return Promise.resolve();
      },
    }
  ],
  minAmount: [
    {
      required: true,
      message: '请输入最低还款金额'
    },
    {
      validator: (_, value) => {
        if (value === 0 || value === '0') {
          return Promise.reject(new Error('输入最低还款金额必须大于0'));
        }
        return Promise.resolve();
      },
    }
  ],
}

const CreditForm = (props) => {
  const [repayment, setRepayment] = useState('minimum')
  const [repaymentOption] = useState([
    {
      value: 'minimum',
      label: '最低还款',
    },
    {
      value: 'fixed',
      label: '固定还款',
    }
  ])

  useEffect(() => {
  }, [])

  const handleSubmit = (values) => {
    const { repayment, amount, interest, minRatio, payment, minAmount } = values

    const monthlyPayment = payment;
    const monthlyRate = interest / 100 / 12;

    // 初始化变量
    let remainingBalance = Number(amount);
    let totalInterest = 0;
    let months = 0;
    const paymentSchedule = [];

    while (remainingBalance > 0 && months < 120) {
      months++;

      const currentMinPayment = Math.max(minAmount, remainingBalance * (minRatio / 100));

      let paymentAmount;
      const interestPayment = remainingBalance * monthlyRate;

      if (repayment === 2) {
        paymentAmount = (remainingBalance + interestPayment < monthlyPayment)
          ? remainingBalance + interestPayment
          : monthlyPayment;
      } else {
        const totalDue = remainingBalance + interestPayment;
        paymentAmount = totalDue < currentMinPayment ? totalDue : currentMinPayment;
      }

      if (paymentAmount < interestPayment) {
        message.error('每月还款额必须大于当月利息');
        return;
      }

      totalInterest += interestPayment;

      const principalPayment = Math.min(paymentAmount - interestPayment, remainingBalance);
      remainingBalance -= principalPayment;

      paymentSchedule.push({
        month: months,
        beginningBalance: (months === 1) ? Number(amount).toFixed(2) : Number(paymentSchedule[months - 2].endingBalance).toFixed(2),
        payment: Number(paymentAmount).toFixed(2),
        interest: Number(interestPayment).toFixed(2),
        principal: Number(principalPayment).toFixed(2),
        endingBalance: Number(remainingBalance).toFixed(2)
      });

      if (remainingBalance <= 0.01 || paymentAmount <= 0.01) {
        remainingBalance = 0;
        break;
      }
    }

    // 计算总还款额
    const totalCost = Number(amount) + Number(totalInterest);

    props.onSubmit && props.onSubmit({
      totalInterest: Number(totalInterest).toFixed(2),
      monthsToPayoff: months,
      totalCost: Number(totalCost).toFixed(2),
      paymentSchedule: paymentSchedule
    })
  }

  return (
    <div className="form-item">
      <Form
        name="credit-form"
        form={props.form}
        labelCol={{ span: 24 }}
        wrapperCol={{ span: 24 }}
        colon={false}
        onFinish={handleSubmit}
        initialValues={{
          repayment: 'minimum',
          interest: 18,
          minAmount: 500
        }}
      >
        <Form.Item label="已用额度(元)" name="amount" rules={rules.amount}>
          <Input placeholder="0" prefix={<RmbIcon width={14} height={14} fill="#999" />} />
        </Form.Item>
        <Form.Item label="年利率" name="interest" rules={rules.interest}>
          <Input placeholder="请输入贷款金额" suffix={<PercentIcon width={14} height={14} fill="#999" />} />
        </Form.Item>
        <Form.Item label="还款方式" name="repayment">
          <ul className="repayment-select" name="repayment">
            {repaymentOption.map((item) => (
              <li
                key={item.value}
                onClick={(e) => {
                  setRepayment(item.value)
                  props.form.setFieldValue('repayment', item.value)
                }}
                className={classnames({
                  active: item.value === repayment
                })}
              >
                {item.label}
              </li>
            ))}
          </ul>
        </Form.Item>
        {
          repayment === 'minimum' && (
            <div className="form-double-column">
              <Form.Item label="最低还款比例" name="minRatio" rules={rules.minRatio}>
                <Input placeholder="请输入还款比例" suffix={<PercentIcon width={14} height={14} fill="#999" />} />
              </Form.Item>
              <Form.Item label="最低还款金额" name="minAmount" rules={rules.minAmount}>
                <Input placeholder="请输入还款金额" prefix={<RmbIcon width={14} height={14} fill="#999" />} />
              </Form.Item>
            </div>
          )
        }
        {
          repayment === 'fixed' && (
            <Form.Item label="每月还款金额(元)" name="payment" rules={rules.payment}>
              <Input placeholder="请输入每月还款金额" prefix={<RmbIcon width={14} height={14} fill="#999" />} />
            </Form.Item>
          )
        }
      </Form>
    </div>
  )
}

export default CreditForm;